import { storeApi, commonApi } from '../../api/index';
import { toast } from "../../utils/modal"
import { getCurrentDate } from "../../utils/util"
import { API_PLATFORM } from '../../utils/config';
// 获取app
var app = getApp();
Page({
  data: {
    platform: API_PLATFORM,
    orderId: null, //预约订单id
    showPopup: false,
    filesHost: app.globalData.filesHost,
    pageParam: {
      page: 1,
      page_size: 10
    },
    storeInfo: {},
    typeList: [],
    selectTypeId: null,
    colorList: [],
    selectColorId: null,
    areaList: [],
    selectAreaId: null,
    personList: [],
    selectPersonId: null,
    dateList: [],
    selectDate: {},
    timeList: [],
    selectTime: {},
    showTimeLength: 9, // 到店时间选择，默认9
    phone: '',
  },
  async getData() {
    try {
      const res = await storeApi.queryStoreList(this.data.pageParam)
      this.setData({
        storeInfo: res.list[0],
      })
      this.getProjectList()
      this.getEmployeeList()
      this.getBusinessDateList() // 获取店铺营业时间
    } catch (e) { }
  },
  async getProjectList() {
    try {
      const storeInfo = this.data.storeInfo
      const res = await storeApi.queryProjectList({ ran_store_id: storeInfo.id })
      this.setData({
        areaList: res.hair_region_list.list,
        colorList: res.hairdye_color_list.list,
        typeList: res.hairdye_type_list.list,
      })
    } catch (e) { }
  },
  async getEmployeeList() {
    try {
      const storeInfo = this.data.storeInfo
      const res = await storeApi.queryEmployeeList({  
        page: 1,
        page_size: 10,
        ran_store_id: storeInfo.id 
      })
      this.setData({
        personList: res.list,
      })
    } catch (e) { }
  },
  async getBusinessDateList() {
    try {
      const storeInfo = this.data.storeInfo
      const res = await storeApi.queryBusinessDateList({
        ran_store_id: storeInfo.id
      })
      this.setData({
        dateList: res.list || [],
      })
      if (res?.list?.length) {
        this.setData({
          selectDate: {
            index: 0,
            date: res.list[0].date_cn,
          }
        })
      } else {
        toast('该门店暂无可预约时间，请联系店员')
      }
    } catch (e) { }
  },
  async getTimeBlockList(date) {
    try {
      const { storeInfo, selectPersonId } = this.data
      const res = await storeApi.queryTimeBlockList({
        ran_store_id: storeInfo.id,
        ran_store_employee_id: selectPersonId,
        date
      })
      if (res.list.length === 0) {
        toast('该门店暂无可预约时间，请联系店员')
        return
      }
      this.setData({
        timeList: res.list,
      })
      const currentTimeIdx = res.list.findIndex(item => item.is_expired == 0)
      if (currentTimeIdx > 0) {
        this.scrollToItem(currentTimeIdx);
      } else {
        this.setData({
          scrollTop: 0
        });
      }

    } catch (e) { }
  },
  scrollToItem(index) {
    // 滚动到当前时间
    let distanceFromTop = 0
    const queryTime = wx.createSelectorQuery();
    queryTime.select('#book-time').boundingClientRect((res) => {
      if (res) {
        distanceFromTop = res.top; // 距离页面顶部的距离
        console.log('距离顶部的距离:', distanceFromTop);
      }
    }).exec();
    const query = wx.createSelectorQuery();
    query.select(`#bookTimeItem-${index}`).boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      if (res[0] && res[1]) {
        const itemTop = res[0].top;
        const scrollOffset = res[1].scrollTop;
        this.setData({
          scrollTop: scrollOffset + itemTop - distanceFromTop
        });
      }
    });
  },
  onSelectType(e) {
    const target = e.currentTarget.dataset;
    this.setData({
      selectTypeId: target.id
    });
  },
  onSelectColor(e) {
    const target = e.currentTarget.dataset;
    this.setData({
      selectColorId: target.id,
    });
  },
  onSelectArea(e) {
    const target = e.currentTarget.dataset;
    this.setData({
      selectAreaId: target.id
    });
  },
  onSelectDate(e) {
    const target = e.currentTarget.dataset;
    if (target.disabled) {
      return;
    }
    this.setData({
      selectDate: {
        index: target.idx,
        date: target.date_cn,
      },
      selectTime: {}
    });
    this.getTimeBlockList(target.date)
  },
  onSelectTime(e) {
    const target = e.currentTarget.dataset;
    if (target.disabled) {
      return;
    }
    this.setData({
      selectTime: {
        index: target.idx,
        time: target.time,
        start_at: target.start_at,
      },
    });
  },
  onSelectPerson(e) {
    const target = e.currentTarget.dataset;
    this.setData({
      selectPersonId: target.id,
    }, ()=>{
      // 选完店员选时间块
      const { dateList } = this.data
      const currentDate = getCurrentDate()
      const date  = dateList.length ? dateList[0].date : currentDate
      this.getTimeBlockList(date)
    });
   
  },
  onLoadMore() {
    this.setData({
      showTimeLength: 9999,
    });
  },
  async onBook() {
    const { selectDate, selectTime, phone, orderId  } = this.data
    if (selectDate.index >= 0 && selectTime.index >= 0 && phone.length == 11) {
      if(orderId){
        this.updateReservationOrder();
      }else{
        this.createReservationOrder();
      }
    }
  },
  async createReservationOrder(){
      try {
        const { storeInfo,selectTypeId, selectColorId, selectAreaId, selectTime, selectPersonId, phone } = this.data
        if(selectTypeId > 0 && selectColorId > 0  && selectAreaId > 0   &&  selectPersonId > 0){
          const res = await storeApi.createReservationOrder({
            ran_store_id: storeInfo.id,
            ran_store_hairdye_type_id: selectTypeId,
            ran_store_hairdye_color_id: selectColorId,
            ran_store_hair_region_id: selectAreaId,
            ran_store_employee_id: selectPersonId,
            start_at: selectTime.start_at,
            phone,
          })
          this.setData({
            showPopup: true
          })
        }
      } catch (err) {
        // console.log(err)
      }
  },
  async updateReservationOrder(){
    try {
      const { storeInfo,selectTypeId, selectColorId, selectAreaId, selectTime, selectPersonId, phone, orderId } = this.data
      const res = await storeApi.updateReservationOrder({
        id: orderId,
        ran_store_id: storeInfo.id,
        ran_store_hairdye_type_id: selectTypeId,
        ran_store_hairdye_color_id: selectColorId,
        ran_store_hair_region_id: selectAreaId,
        ran_store_employee_id: selectPersonId,
        start_at: selectTime.start_at,
        // status: 1, // 只是调整项目，所以状态还是待开始
        phone,
      })
      this.setData({
        showPopup: true
      })
    } catch (err) {
      // console.log(err)
    }
  },
  async getInfo(id) {
    try {
      const res = await storeApi.getReservationOrderDetail({ id })
      this.setData({
        selectTypeId: res.hairdye_type_info.id,
        selectColorId: res.hairdye_color_info.id,
        selectAreaId: res.hair_region_info.id,
        selectPersonId: res.replace_reservation_employee_id,
        phone: res.phone,
        checkTime: res.start_time_block_info.time
      })

      // 计算反显日期
      const checkDate = res.start_time_block_info.date
      const { dateList } = this.data
      const index = dateList.findIndex((item) => item.date === checkDate)
      this.setData({
        selectDate:{
          index: index,
          date: dateList[index].date_cn,
        }
      })
      await this.getTimeBlockList(dateList[index].date)

  
      // 计算反显时间
      const checkTime = res.start_time_block_info.time
      const { timeList } = this.data
      const indexTime = timeList.findIndex((item) => item.time === checkTime)
      this.setData({
        selectTime:{
          index: indexTime,
          time: timeList[indexTime].time,
          start_at: timeList[indexTime].start_at,
        }
      })
    } catch (err) { 
      console.log(err)
    }
  },
  onClose() {
    this.setData({
      showPopup: false,
    })
  },
  onSure() {
    wx.navigateTo({
      url: `/pages/mytask/mytask`,
    });
  },
  async onLoad(options) {
    await this.getData()
    if(options?.id){
      this.setData({
        orderId: options.id,
      })
      this.getInfo(options.id)
       wx.setNavigationBarTitle({
        title: '调整项目',
      });
    }
  },
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {
    return {
      title: '频繁染白发，就找染博士',
      imageUrl:
        'https://ranboss.oss-cn-beijing.aliyuncs.com/ranstore/share.png',
    };
  },
});
